from base64 import decodestring
import ZSI, os, sys, thread
import AuthenticationService, AccountsService
from .SOAPServicesTypes import serviceTypes
from .WSContext import WSContext
from ZSI.TCcompound import Struct
from ZSI.ServiceContainer import ServiceSOAPBinding, SOAPRequestHandler, GetSOAPContext
from Converters import convertFromSOAPAccount

_wsContexts = {}
def getWSContext():
    global _wsContexts
    return _wsContexts[thread.get_ident()]
    
class loginRequest:
    def __init__(self, **kw):
        """Keyword parameters:
        login -- part login
        """
        self._login =  kw.get("login")
loginRequest.typecode = Struct(pname=("urn:HomebuhService.wsdl","login"), ofwhat=[ZSI.TC.String(pname="login", aname="_login", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True)], pyclass=loginRequest, encoded="urn:HomebuhService.wsdl")

class loginResponse:
    def __init__(self, **kw):
        """Keyword parameters:
        user -- part user
        """
        self._user =  kw.get("user")
loginResponse.typecode = Struct(pname=("urn:HomebuhService.wsdl","loginResponse"), ofwhat=[serviceTypes.User_Def(pname="user", aname="_user", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True)], pyclass=loginResponse, encoded="urn:HomebuhService.wsdl")

class registerAccountRequest:
    def __init__(self, **kw):
        """Keyword parameters:
        account -- part account
        """
        self._account =  kw.get("account")
registerAccountRequest.typecode = Struct(pname=("urn:HomebuhService.wsdl","registerAccount"), ofwhat=[serviceTypes.Account_Def(pname="account", aname="_account", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True)], pyclass=registerAccountRequest, encoded="urn:HomebuhService.wsdl")

class registerAccountResponse:
    def __init__(self, **kw):
        """Keyword parameters:
        accountId -- part accountId
        """
        self._accountId =  kw.get("accountId")
registerAccountResponse.typecode = Struct(pname=("urn:HomebuhService.wsdl","registerAccountResponse"), ofwhat=[ZSI.TCnumbers.Iinteger(pname="accountId", aname="_accountId", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True)], pyclass=registerAccountResponse, encoded="urn:HomebuhService.wsdl")

class getAccountsRequest:
    def __init__(self, **kw):
        """Keyword parameters:
        """
getAccountsRequest.typecode = Struct(pname=("urn:HomebuhService.wsdl","getAccounts"), ofwhat=[], pyclass=getAccountsRequest, encoded="urn:HomebuhService.wsdl")

class getAccountsResponse:
    def __init__(self, **kw):
        """Keyword parameters:
        accounts -- part accounts
        """
        self._accounts =  kw.get("accounts")
getAccountsResponse.typecode = Struct(pname=("urn:HomebuhService.wsdl","getAccountsResponse"), ofwhat=[serviceTypes.ArrayOfAccounts_Def(pname="accounts", aname="_accounts", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True)], pyclass=getAccountsResponse, encoded="urn:HomebuhService.wsdl")

class WSRequestHandler(SOAPRequestHandler):

    def do_POST(self):
        threadId = thread.get_ident()
        _wsContexts[threadId] = WSContext()
        SOAPRequestHandler.do_POST(self)
        if _wsContexts.has_key(thread.get_ident()):
            del _wsContexts[thread.get_ident()]

class HomebuhWebService(ServiceSOAPBinding):
    soapAction = {}
    root = {}
    
    _wsdl = "".join(open(os.path.join(sys.path[0], "homebuh.wsdl")).readlines())

    def __init__(self, post='/HomebuhService', **kw):
        ServiceSOAPBinding.__init__(self, post)
        
    def soap_login(self, ps, **kw):
        request = ps.Parse(loginRequest.typecode)
        response = loginResponse()
        user = AuthenticationService.getUser(request._login)
        
        class User:
            _login = user.login
            _name = user.name
            _email = user.email
            
        response._user = User
        return request, response
    
    def soap_registerAccount(self, ps, **kw):
        request = ps.Parse(registerAccountRequest.typecode)
        response = registerAccountResponse()
        response._accountId = AccountsService.saveOrUpdateAccount(getWSContext().login, convertFromSOAPAccount(request._account))
        return request, response

    def soap_getAccounts(self, ps, **kw):
        from database import Account
        request = ps.Parse(getAccountsRequest.typecode)
        response = getAccountsResponse()
        class ArrayOfAccounts:
            _account = map(Account.getData, AccountsService.getAccounts(getWSContext().login)) 
        response._accounts = ArrayOfAccounts
        return request, response

    def authorize(self, auth_info, post, action):
        context = GetSOAPContext()
        if (context.httpheaders.has_key('authorization')):
            authHeader = context.httpheaders['authorization'].split(' ')
            if (len(authHeader) == 2 and authHeader[0].lower() == 'basic'):
                authHeader = decodestring(authHeader[1])
                user, password = authHeader.split(':')
                getWSContext().login = user
                return AuthenticationService.isAuthenticated(user, password)
        return 0

    soapAction['urn:HomebuhService.wsdl#login'] = 'soap_login'
    root[(loginRequest.typecode.nspname,loginRequest.typecode.pname)] = 'soap_login'

    soapAction['urn:HomebuhService.wsdl#registerAccount'] = 'soap_registerAccount'
    root[(registerAccountRequest.typecode.nspname,registerAccountRequest.typecode.pname)] = 'soap_registerAccount'

    soapAction['urn:HomebuhService.wsdl#getAccounts'] = 'soap_getAccounts'
    root[(getAccountsRequest.typecode.nspname,getAccountsRequest.typecode.pname)] = 'soap_getAccounts'
